<template>
  <div class="user-detail-box">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 搜索位置结构 -->
      <el-row :gutter="14">
        <el-col :span="8">
          <el-input placeholder="请输入名称" class="input-with-select" size="mini" v-model="queryInfo.query" clearable @clear="getUserInfoList">
            <el-button slot="append" icon="el-icon-search" @click="getUserInfoList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" size="mini" @click="addUserDialog = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表 elementui有自动循环功能 -->
      <el-table :data="userInfoList" stripe border>
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="create_time"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <!-- 定义开关模板 添加 slot-scope='scope'才能获取到上面列信息中数据 scope.row用户信息对象-->
          <template slot-scope="scope">
            <!-- change事件是elementui 中switch开关提供监听状态变化的方法 -->
            <el-switch v-model="scope.row.mg_state" active-color="#BBE6D6" inactive-color="#f4f8f8" @change="changUserStatus(scope.row)"> </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" circle size="mini" @click="showChangDailog(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" circle size="mini" @click="deleteUser(scope.row.id)"></el-button>
            <el-tooltip effect="dark" content="角色分配" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-star-off" circle size="mini" @click="showRolsDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页结构 -->
      <!-- page-sizes单页可显示多少条数据 total总共有多少页 current-page当前页码 page-size单页显示多少条数据 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- Dialog对话框  给对话框绑定close事件（elementui）提供的事件，对话框关闭时触发-->
    <el-dialog title="添加用户" :visible.sync="addUserDialog" width="50%" @close="addUserClose">
      <el-form :model="addUser" :rules="addUserFormrules" ref="ruleFormref" label-width="80px" class="demo-ruleForm">
        <!-- prop属性绑定校验规则 v-model将来是要发送给后台的，所以名字由后台来定-->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUser.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUser.password" placeholder="请输入密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUser.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addUser.mobile" placeholder="请输入手机号"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialog = false">取 消</el-button>
        <el-button type="primary" @click="addUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户" :visible.sync="changeUserDialog" width="50%">
      <el-form :model="changeUser" :rules="changeUserFormrules" ref="chageruleFormref" label-width="80px" class="demo-ruleForm">
        <!-- prop属性绑定校验规则 v-model将来是要发送给后台的，所以名字由后台来定-->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="changeUser.username" placeholder="请输入用户名" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="changeUser.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="changeUser.mobile" placeholder="请输入手机号"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="changeUserDialog = false">取 消</el-button>
        <el-button type="primary" @click="changeUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="rolsDialog" width="50%" @close="setRolsClose">
      <div>
        <p>用户： {{ userInfo.username }}</p>
        <p>角色： {{ userInfo.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id"> </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rolsDialog = false">取 消</el-button>
        <el-button type="primary" @click="setUserRols">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'users',
  data() {
    return {
      //定义请求用户信息查询参数
      queryInfo: {
        query: '',
        pagenum: 1, //页码
        pagesize: 5, //单页数据大小
      },
      userInfoList: null,
      total: 0,
      //添加用户对话框显隐
      addUserDialog: false,
      //添加用户对话框显隐
      changeUserDialog: false,
      //添加用户对象
      addUser: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      //修改用户对象
      changeUser: {},
      //添加用户校验规则
      addUserFormrules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '长度在 6 到 15 个字符',
            trigger: 'blur',
          },
        ],
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          {
            pattren: /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/,
            message: '邮箱格式不正确',
            trigger: 'blur',
          },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattren: /^1[3|4|5|7|8][0-9]{9}$/,
            message: '手机号格式不正确',
            trigger: 'blur',
          },
        ],
      },
      //修改用户校验规则
      changeUserFormrules: {
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          {
            pattren: /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/,
            message: '邮箱格式不正确',
            trigger: 'blur',
          },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattren: /^1[3|4|5|7|8][0-9]{9}$/,
            message: '手机号格式不正确',
            trigger: 'blur',
          },
        ],
      },
      //控制分配角色对话框显隐
      rolsDialog: false,
      userInfo: '',
      rolesList: [],
      selectedRoleId: '',
    }
  },
  created() {
    this.getUserInfoList()
  },
  methods: {
    //获取用户信息列表方法：
    async getUserInfoList() {
      var { data: res } = await this.$http.get('users', {
        params: this.queryInfo,
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败') //elementui提供的方法
      }
      this.userInfoList = res.data.users
      //   console.log(this.userInfoList);
      this.total = res.data.total
    },
    //监听pagesize大小改变的方法
    handleSizeChange(pagesize) {
      this.queryInfo.pagesize = pagesize
      this.getUserInfoList()
    },
    //监听当前页pagenum改变的方法
    handleCurrentChange(pagenum) {
      this.queryInfo.pagenum = pagenum
      this.getUserInfoList()
    },
    //监听switch中用户状态的变化，
    async changUserStatus(userInfo) {
      // console.log(userInfo)
      const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      //    console.log(res)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('用户状态更新失败')
      }
      this.$message.success('用户状态更新成功！')
    },
    //监听添加用户对话框关闭触发事件，resetFields对该表单项进行重置，将其值重置为初始值并移除校验结果
    addUserClose() {
      this.$refs.ruleFormref.resetFields() //该方法elementui提供
    },
    //添加用户
    //elementui提供了validate()方法进行初步校验，里面有个回调函数，
    //回调函数接收一个参数表示校验是否通过
    addUserInfo() {
      this.$refs.ruleFormref.validate(async (vali) => {
        if (!vali) {
          return
        }
        const { data: res } = await this.$http.post('users', this.addUser)
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败')
        }
        //校验成功可以添加数据后，我们需要关闭对话框
        this.addUserDialog = false
        //刷新用户信息列表
        this.getUserInfoList()
        //添加成功后给出相应的提示
        this.$message.success('用户添加成功！')
      })
    },
    //显示修改用户对话框
    async showChangDailog(id) {
      const { data: res } = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户失败')
      }
      this.changeUser = res.data
      this.changeUserDialog = true
    },
    //向后台修改用户信息
    changeUserInfo() {
      //修改前同样需要表单校验
      this.$refs.chageruleFormref.validate(async (valid) => {
        if (!valid) {
          return
        }
        //表单校验成功可以进行修改，向后台发送修改请求
        const { data: res } = await this.$http.put(`users/${this.changeUser.id}`, {
          email: this.changeUser.email,
          mobile: this.changeUser.mobile,
        })

        if (res.meta.status !== 200) {
          return this.$message.error('修改用户出错')
        }
        this.changeUserDialog = false
        this.getUserInfoList()
        this.$message.success('成功修改用户')
      })
    },
    //删除用户信息
    deleteUser(id) {
      //下面方法为elementui massegeBox确定消息提供
      this.$confirm('确定要删除用户吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`users/${id}`)
          if (res.meta.status !== 200) {
            return this.$message.error('删除失败！')
          }
          this.getUserInfoList()
          this.$message.success('删除成功！')
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 分配角色
    async setUserRols() {
      if (!this.selectedRoleId) {
        this.$message.error('请选择要分配的角色！')
      }
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}`, { rid: this.selectedRoleId })
      if (res.meta.status !== 200) {
        return this.$message.error('角色更新失败！')
      }
      this.$message.success('角色更新成功！')
      this.getUserInfoList()
      this.rolsDialog = false
    },
    //分配角色对话框取消关闭时触发
    setRolsClose() {},
    //点击分配角色按钮触发
    async showRolsDialog(userInfo) {
      this.rolsDialog = true
      this.userInfo = userInfo
      //获取角色列表给下拉列表框渲染
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.rolesList = res.data
      console.log(this.rolesList)
    },
  },
}
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
</style>